package com.app.medicalcontrol.fragment;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import com.app.medicalcontrol.R;
import com.app.medicalcontrol.back.CameraCallBack;
import com.app.medicalcontrol.basis.BaseMainFragment;
import com.app.medicalcontrol.basis.BasisApp;
import com.app.medicalcontrol.bean.JavaScriptinterface;
import com.app.medicalcontrol.bean.LoginBean;
import com.app.medicalcontrol.event.WebReLoadEvent;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import my.LogUtil;
import my.http.HttpRestClient;
import my.http.MyHttpListener;

import static android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;


@SuppressLint("SetJavaScriptEnabled")
public class WebViewX5Fragment extends BaseMainFragment implements CameraCallBack {

    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;
    /**
     * 选择系统图片Request Code
     */
    public static final int REQUEST_IMAGE = 112;

    /**
     * 请求CAMERA权限码
     */
    public static final int REQUEST_CAMERA_PERM = 101;
    private  int index;

    com.tencent.smtt.sdk.WebView mWebView;
    String wapurl;
    private String title;
    private boolean haveBackBtn = false;

    public static WebViewX5Fragment getInstance(String url) {
        WebViewX5Fragment fragment = new WebViewX5Fragment();
        fragment.wapurl = url;
        return fragment;
    }

    public static WebViewX5Fragment getInstance(String url, String title) {
        WebViewX5Fragment fragment = new WebViewX5Fragment();
        fragment.wapurl = url;
        fragment.title = title;
        return fragment;
    }

    public static WebViewX5Fragment getInstance(String url, String title, boolean haveBackBtn) {
        WebViewX5Fragment fragment = new WebViewX5Fragment();
        fragment.wapurl = url;
        fragment.title = title;
        fragment.haveBackBtn = haveBackBtn;
        return fragment;
    }

    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        setContentView(R.layout.base_webview_local_x5);

        setTitleRightButton(R.mipmap.top_icon_msg, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getMessageInfo(v);
            }
        });

        if (haveBackBtn) {
            setTitleLeftButton(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mWebView.goBack();
                }
            });
        }


        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        // mWebView.getSettings().setSupportZoom(true);
        // mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.setInitialScale(20);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setSavePassword(false);
//         mWebView.getSettings().setAppCachePath("external/chromium/net/disk_cache/");
        // mWebView.getSettings().setDisplayZoomControls(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setSaveEnabled(true);
        mWebView.getSettings().setAllowContentAccess(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setDatabaseEnabled(true);
        // setZoomControlGone(mWebView);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setMixedContentMode(MIXED_CONTENT_ALWAYS_ALLOW);
        mWebView.clearCache(true);
//		webSet.setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWebView.setWebViewClient(new MyWebViewClient());
//        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebChromeClient(chromeClient);
        mWebView.requestFocus();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        initUrl();
        mWebView.addJavascriptInterface(new JavaScriptinterface(mContext,this), "android");

    }

    @Override
    public void onDestroyView() {
        if (mWebView != null) {
            try {
                mWebView.setWebViewClient(null);
                mWebView.destroy();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        super.onDestroyView();
    }

    private void initUrl() {
        if (wapurl == null || wapurl.equals("")) {
            BasisApp.showToast("网页地址不存在");
        }
        LogUtil.i("initUrl---->" + wapurl);

        setTitle(title + "");

//        if (wapurl.endsWith(".html")) {
//            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        } else {
//            mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//        }
        // myProgressDialog.show();
        mWebView.loadUrl(wapurl);
    }


    @Override
    public boolean onBackPressedSupport() {
        String a = mWebView.getUrl().toString().trim();
        String b = wapurl.toString().trim();
        if (a.equals(b)) {
            return super.onBackPressedSupport();
        } else {
            mWebView.goBack();
            return true;
        }
    }

    @SuppressLint("NewApi")
    class MyWebViewClient extends WebViewClient {
        String loginCookie;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            // if(myProgressDialog != null &&
            // !myProgressDialog.isShowing())myProgressDialog.show();
            LogUtil.i("shouldOverrideUrlLoading---->" + url);
            if (url.startsWith("mailto:") || url.startsWith("geo:")
                    || url.startsWith("tel:") || url.indexOf(".3gp") != -1 || url.indexOf(".mp4") != -1
                    || url.indexOf(".flv") != -1
                    || url.indexOf(".swf") != -1) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

            } else if (url.startsWith("weixin://wap/pay?")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            } else {
                //H5微信支付要用，不然说"商家参数格式有误"
                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Referer", "https://cloud.keytop.cn/");
                mWebView.loadUrl(url, extraHeaders);

//                mWebView.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            // CookieManager cookieManager = CookieManager.getInstance();
            // loginCookie = cookieManager.getCookie(url);
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            // CookieManager cookieManager = CookieManager.getInstance();
            // cookieManager.setCookie(url, loginCookie);
            super.onPageFinished(view, url);
            dismissProgress();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
            if (!mContext.isFinishing()) {
                showProgress();
            }
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
//            super.onReceivedSslError(webView, sslErrorHandler, sslError);
            sslErrorHandler.proceed();
        }
    }

    public boolean parseScheme(String url) {

        if (url.contains("platformapi/startapp")) {
            return true;
        } else if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
                && (url.contains("platformapi") && url.contains("startapp"))) {
            return true;
        } else {
            return false;
        }
    }

    private WebChromeClient chromeClient = new WebChromeClient() {

        @Override
        public boolean onJsConfirm(WebView arg0, String arg1, String arg2, JsResult arg3) {
            return super.onJsConfirm(arg0, arg1, arg2, arg3);
        }

        View myVideoView;
        View myNormalView;
        IX5WebChromeClient.CustomViewCallback callback;

        ///////////////////////////////////////////////////////////
        //  `

        /**
         * 全屏播放配置
         */
        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
            View normalView = mContext.findViewById(R.id.webview);
            ViewGroup viewGroup = (ViewGroup) normalView.getParent();
            viewGroup.removeView(normalView);
            viewGroup.addView(view);
            myVideoView = view;
            myNormalView = normalView;
            callback = customViewCallback;
        }

        @Override
        public void onHideCustomView() {
            if (callback != null) {
                callback.onCustomViewHidden();
                callback = null;
            }
            if (myVideoView != null) {
                ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                viewGroup.removeView(myVideoView);
                viewGroup.addView(myNormalView);
            }
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            uploadFile = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            mContext.startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER);
        }

        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            uploadFile = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            mContext.startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER);
        }

        @Override
        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String captureType) {
            LogUtil.i("openFileChooser--->");
            uploadFile = uploadFile;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            mContext.startActivityForResult(Intent.createChooser(i, "选择文件"),
                    FILE_CHOOSER);
            super.openFileChooser(uploadFile, acceptType, captureType);
        }

        // For Android 5.0+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            LogUtil.i("openFileChooser--5.0->");
            mUploadCallbackAboveL = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            mContext.startActivityForResult(
                    Intent.createChooser(i, "选择文件"),
                    FILE_CHOOSER);
            return true;
        }

        @Override
        public void onReceivedTitle(WebView arg0, final String arg1) {
            super.onReceivedTitle(arg0, arg1);
//            Log.i("yuanhaizhou", "webpage title is " + arg1);

        }
    };

    private ValueCallback<Uri> uploadFile;
    ValueCallback<Uri[]> mUploadCallbackAboveL;
    private static final int FILE_CHOOSER = 22;


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILE_CHOOSER
                || mUploadCallbackAboveL == null) {
            return;
        }
        LogUtil.i("onActivityResultAboveL-------->" + resultCode);
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(WebReLoadEvent messageEvent) {
        showProgress();
        LoginBean.refreshToken(new LoginBean.Token_Listener() {
            @Override
            public void onSuccess() {
                String aa = wapurl.substring(0, wapurl.indexOf("?ctoken"));
                aa = aa + "?ctoken=" + LoginBean.getInstance().getToken().getValue();
                mWebView.loadUrl(aa);
            }

            @Override
            public void onFailure() {

            }

            @Override
            public void onFinish() {
                dismissProgress();
            }
        });
    }



    @Override
    public void showCamera(int index) {
        this.index = index;
        Intent intent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(intent, WebViewX5Fragment.REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
//            处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mWebView.loadUrl("javascript:getNumber('"+result+"','"+index+"')");
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    showToast("解析二维码失败");
                }
            }
        }


        else if (requestCode == REQUEST_CAMERA_PERM) {

        }
    }

}
